local util = require "util"
local conf = require "conf"
local require = require
local setmetatable = setmetatable
local error = error
local table = table
local ngx = ngx
local os = os
local string = string
local io = io
local tonumber = tonumber
package.cpath = "/usr/nginx/?.so;;"
local json = require 'cjson'
module(...)
_VERSION = '0.1'
_STATIC_FILE_PATH = '/opt/xyitech/static/'

function create(user, args)
    local version_id, version_series_no, file_name, comment, origin = args.version_id, args.version_series_no, args.file_name, args.comment, args.origin
    local db = conf.get_mysql()
    local vals = {}

    if version_id then
        vals[#vals + 1] = "version_id = '" .. version_id .. "'"
    end

    if version_series_no then
        vals[#vals + 1] = "version_series_no = '" .. version_series_no .. "'"
    end

    if comment then
        vals[#vals + 1] = "comment = '" .. comment .. "'"
    end
    if file_name then
        local file,err = io.open(_STATIC_FILE_PATH .. file_name)
        if err then
            ngx.print(json.encode({
                err = 1,
                msg = err
            }))
            ngx.exit(200)
        end
        local len = file:seek("end")
        vals[#vals + 1] = "file_length = " .. len
        file:close()
        vals[#vals + 1] = "file_name = '" .. file_name .. "'"
    end
    if origin then
        vals[#vals + 1] = "origin = '" .. origin .. "'"
    end
    vals[#vals + 1] = "create_time = " .. os.time()
    vals[#vals + 1] = "update_time = " .. os.time()
    
    local res = db:query("INSERT INTO `version` SET " .. table.concat(vals, ","))
    return res
end

function createController(user, args)
    local res = create(user, args)
    local db = conf.get_mysql()
    if not res or res.affected_rows < 1 then
        ngx.print(json.encode({
            err = 1,
            msg = '创建失败'
        }))
        ngx.exit(200)
    else
        local insert_id = res.insert_id
        if insert_id < 1 then
            res = db:query("SELECT LAST_INSERT_ID() AS insert_id")
            if res and res[1] and res[1].insert_id then
                insert_id = res[1].insert_id
            end
        end
        ngx.print(json.encode({
            err = 0,
            id = insert_id,
            msg = '创建成功'
        }))
        ngx.exit(200)
    end
end

function search(user, args)
    local page_no, page_size, version_id, id, version_series_no, comment = tonumber(args.page_no), tonumber(args.page_size), args.version_id, args.id, args.version_series_no, args.comment
    local db = conf.get_mysql()
    local sql = nil
    local count = nil
    local res = nil
    
    sql = "SELECT * FROM `version` WHERE 1=1"
    if version_id then
        sql = sql ..  " AND `version`.version_id like '%" .. version_id .. "%'"
    end

    if version_series_no then
        sql = sql ..  " AND `version`.version_series_no like '%" .. version_series_no .. "%'"
    end

    if id then
        sql = sql ..  " AND `version`.id = " .. id
    end

    if args.origin then
        sql = sql ..  " AND `version`.origin = '" .. args.origin .. "'"
    end

    if args.state then
        sql = sql .. " AND `version`.state = " .. args.state
    end
    local count = #(db:query(sql) or {})

    if page_no and page_size then
        sql = sql .. " LIMIT " .. (page_no * page_size) .. "," .. page_size
    end
    ngx.log(ngx.ERR, sql)
    res = db:query(sql)
    return res, count
end

function searchController(user, args)
    local res, count = search(user, args)
    if not res then
        ngx.print(json.encode({
            err = 1,
            msg = {}
        }))
        ngx.exit(200)
    else
        ngx.print(json.encode({
            err = 0,
            msg = res,
            count = count
        }))
        ngx.exit(200)
    end
end

function update(user, args)
    local id, version_id, version_series_no, comment = args.id, args.version_id, args.version_series_no, args.comment
    local db = conf.get_mysql()
    local vals = {}
    
    if version_id then
        vals[#vals + 1] = "version_id = '" .. version_id .. "'"
    end

    if version_series_no then
        vals[#vals + 1] = "version_series_no = '" .. version_series_no .. "'"
    end

    if comment then
        vals[#vals + 1] = "comment = '" .. comment .. "'"
    end

    if args.state then
        vals[#vals + 1] = "state = " .. args.state .. ""
    end
    vals[#vals + 1] = "update_time = " .. os.time()

    local sql = "UPDATE `version` SET " .. table.concat(vals, ",") .. " WHERE id = " .. id
    ngx.log(ngx.ERR, sql)
    local res = db:query(sql)--AND aid = " .. aid
    return res
end

function updateController(user, args)
    if not id then
        ngx.print(json.encode({
            err = 1,
            msg = "缺少id",
        }))
        ngx.exit(200)
    end

    local res = update(user, args)
    if not res or res.affected_rows < 1 then
        ngx.print(json.encode({
            err = 1,
            msg = '更新失败'
        }))
        ngx.exit(200)
    else 
        ngx.print(json.encode({
            err = 0,
            msg = '更新成功'
        }))
        ngx.exit(200)
    end
end

function delete(user, args)
    local id = args.id
    local db = conf.get_mysql()

    local res = db:query("DELETE FROM `verison` WHERE id = " .. id)
    return res
end

function deleteController(user, args)
    if not args.id then
        ngx.print(json.encode({
            err = 2,
            msg = '缺少id'
        }))
    end
    local res = delete(user, args)
    if not res or res.affected_rows < 1 then
        ngx.print(json.encode({
            err = 1,
            msg = '更新失败'
        }))
        ngx.exit(200)
    else 
        ngx.print(json.encode({
            err = 0,
            msg = res
        }))
        ngx.exit(200)
    end
end

function setUpdateTime(uid, aid, aids, args)
    local conf = require "conf"
    local redis = conf.get_redis()
    local startTime = args.startTime or 0
    local endTime = args.endTime or 24
    local res, err = red:set("startTime", startTime)
    local res, err = red:set("endTime", endTime)
    if err then
        ngx.print(json.encode({
            err = 1,
            msg = '设置失败'
        }))
        ngx.exit(200)
    else 
        ngx.print(json.encode({
            err = 0,
            msg = res
        }))
        ngx.exit(200)
    end
end

function getLatestVersion(user, args)
    local db = conf.get_mysql()
    local sql = 'SELECT DISTINCT version_id FROM `version` WHERE 1'
    local res = db:query(sql)
    return res
end

function getLatestVersionController(user, args)
    local res = getLatestVersion(user, args)
    if not res or #res == 0 then
        ngx.print(json.encode({
            err = 1,
            msg = '获取版本号失败'
        }))
        ngx.exit(200)
    else
        util.sortVersionId(res)
        ngx.print(json.encode({
            err = 0,
            msg = res[#res]
        }))
        ngx.exit(200)
    end
end
function getUpdateTime(user, args)
    local redis = conf.get_redis()
    local startTime = args.startTime or 0
    local endTime = args.endTime or 24
    local startTime, err = red:get("startTime")
    local endTime, err = red:set("endTime")
    if err then
        ngx.print(json.encode({
            err = 1,
            msg = '获取失败'
        }))
        ngx.exit(200)
    else 
        ngx.print(json.encode({
            err = 0,
            msg = {
                startTime = startTime,
                endTime = endTime
            }
        }))
        ngx.exit(200)
    end
end

function default(args)
    local user = conf.parse_token(args, "version")
    if args.action == 'search' then
        searchController(user, args)
    elseif args.action == 'create' then
        createController(user, args)
    elseif args.action == 'update' then
        updateController(user, args)
    elseif args.action == 'delete' then
        deleteController(user, args)
    elseif args.action == 'setUpdateTime' then
        setUpdateTime(user, args)
    elseif args.action == 'getUpdateTime' then
        getUpdateTime(user, args)
    elseif args.action == 'getLatestVersion' then
        getLatestVersionController(user, args)
    end
end

local class_mt = {
    __newindex = function (table, key, val)
        error('attempt to write to undeclared variable "' .. key .. '"')
    end
}
setmetatable(_M, class_mt)
